﻿
using Microsoft.AspNetCore.Builder;
using RayD.Core;
using System;
using System.IO;
using System.Linq;

namespace RayD.App.Setup
{
    /// <summary>
    /// 中间件配置类
    /// </summary>
    public static class MiddlewareSetup
    {
        /// <summary>
        /// 请求响应 中间件
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static void UseReuestResponseLog(this IApplicationBuilder app)
        {
            if (AppSettings.Middleware.RequestResponseLog.Enabled)
            {
                //开启日志记录(操作日志、异常日志)
                app.UseMiddleware<RequRespLogMid>();
            }
        }

        /// <summary>
        /// Swagger 中间件
        /// </summary>
        /// <param name="app"></param>
        /// <param name="streamHtml"></param>
        public static void UseSwaggerMid(this IApplicationBuilder app, Func<Stream> streamHtml)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //根据版本名称倒序 遍历展示
                typeof(ApiVersion).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");
                });
                // 将swagger首页，设置成我们自定义的页面，记得这个字符串的写法：{项目名.index.html}
                if (streamHtml.Invoke() == null)
                {
                    var msg = "index.html的属性，必须设置为嵌入的资源";
                    throw new Exception(msg);
                }
                c.IndexStream = streamHtml;
                c.RoutePrefix = "";//路径配置，设置为空，表示直接访问该文件
                c.DefaultModelsExpandDepth(-1); //不显示model
            });
        }
    }
}
